import React from 'react';
import style from './style.objective-all';
import { Progress, Link, Select, Loading } from 'sq-ui';
import { bindActionCreators } from 'redux'
import { Checkbox } from '../../ui-components';
import { connect } from 'react-redux'
import cx from 'classnames';
import * as okrAction from '../../actions/okr.action'
import moment from 'moment';
import util from '../../util';

const IMAGES_PATH = process.env.NODE_ENV === 'production'? './static/images': './static/src/images'

function ObjectiveItem(props) { // 组装列表方法
  const {
    objectivePeriodOwnerName,
    ownerId,
    content,
    objectiveId,
    priority,
    deadline,
    progress,
    currentAmount,
    goalAmount,
    progressMetricType,
    startingAmount,
    unit,
    directorList,
    lastModifiedTime,
    type,
  } = props;
  return (
    <div className={style.item}>
      <Link className={style.team} label={`${objectivePeriodOwnerName}`}
        to={type == 3 ? `/okr?type=3&userId=${ownerId}` : type == 4 ? `/okr?type=4&projectTeamId=${ownerId}` : `/okr?type=${type}&teamId=${ownerId}`}
        // to={type == 3 ? `/okr/objective-targetAll?userId=${ownerId}` : type == 4 ? `/okr?type=4&projectTeamId=${ownerId}` : `/okr?type=${type}&teamId=${ownerId}`}
      />
      <Link className={style.content} label={content} to={`/okr/objectives/${objectiveId}`}/>
      <span style={{ width: '43px', marginLeft: '33px' }}>
        <span className={cx(style['item-priority'], style['priority-' + (+priority+1)])}>
          <span>
            { priority == 0? '极高': priority == 1? '高': priority == 2? '中': '低' }
          </span>
        </span>
      </span>
      <span className={style.deadline}>
        { +deadline ? util.dateFormat(new Date(deadline), 'yyyy年MM月dd日') : '' }
      </span>
      <Progress width={90} height={8} value={progress* 100} className={style.progress}
        label={progressMetricType != 1? v => `${currentAmount}/${goalAmount}${unit}（初始值：${startingAmount}）`: null}
        line labelAnimation/>
      <span className={style['directors-wrapper']}>
        {
          !util.isNull(directorList)? (
            <span className={style['directors']}>
              {
                directorList.slice(0, 3).map((v, i) => {
                  const { coreUserProfileVO: u } = v;
                  if (i == directorList.slice(0, 3).length-1) {
                    return <Link target="_blank" key={i} label={`${u.fullName} `} to={`/okr/objective-targetAll?userId=${u.userId}`} />;
                  }
                  return <Link target="_blank" key={i} label={`${u.fullName}、`} to={`/okr/objective-targetAll?userId=${u.userId}`} />;
                })
              }
              { directorList.length > 3 ? <span>等人</span> : null }
            </span>
          ): null
        }
      </span>
      <span className={style['last-update']}>{moment(lastModifiedTime).fromNow()}</span>
    </div>
  );
}

export default
@connect(({ okr }) => ({ okr }), dispatch => ({actions: bindActionCreators({...okrAction }, dispatch)}))
class ObjectiveAll extends React.Component {

  state = {
    loading: true,
  };

  static contextTypes = {
    router: React.PropTypes.object
  }

  pageNumber = this.props.location.query.pageNumber || 1;
  pageSize = 15;

  handleChangeProgress(value) { // 进展情况
    this.query({
      progressStatus: +value + 1,
      pageNumber: 1,
    });
  }

  handleChangePriority(value) { // 优先级筛选
    this.query({
      priority: +value - 1,
      pageNumber: 1,
    });
  }

  handleToggleAboutMe() {
    const { query } = this.props.location;
    const { aboutMe } = query;

    this.query({
      aboutMe: (aboutMe == null || aboutMe === 'false') ? 'true': 'false',
      pageNumber: 1,
    });
  }

  query(obj) { // 根据不同搜索条件去筛选
    const { query, pathname } = this.props.location;
    this.context.router.push({
      query: {
        ...query,
        ...obj,
      },
      pathname,
    });
  }

  fetchObjectives(props) { // 根据筛选条件查询目标
    props = props || this.props;
    const { userId, pageNumber=this.pageNumber, orderItem=1, aboutMe, priority=-1, progressStatus=1 } = props.location.query;
    this.props.actions.fetchAllTargetObjective({
      userId,
      orderItem,
      priority,
      progressStatus,
      pageNumber,
      aboutMe: true,
      pageSize: this.pageSize,
    });
  }

  componentDidMount() {
    this.fetchObjectives();
  }

  componentWillReceiveProps(props) {
    if (!util.isShallowEqual(props.location.query, this.props.location.query)) {
      this.fetchObjectives(props);
      this.resetOkr();
    }

    if (this.props.okr.all && !props.okr.all) {
      this.setState({
        loading: true,
      });
    } else if (!this.props.okr.all && props.okr.all) {
      this.setState({
        loading: false,
      });
    }
  }

  componentWillUnmount() {
    this.props.actions.resetOkr();
  }

  resetOkr() {
    this.pageNumber = 1;
    this.props.actions.resetOkr();
  }

  renderFilter() { // 条件搜索
    const { query } = this.props.location;
    const { orderItem } = query;
    const link = n => `/okr/objective-targetAll?${util.body({...query, orderItem: n, pageNumber: 1})}`
    const getOrder = n => orderItem == null ? -n : Math.abs(n) == Math.abs(orderItem) ? -orderItem : -n;
    const active = n => Math.abs(n) == Math.abs(orderItem) && orderItem < 0;
    return (
      <div className={cx(style.filters, { [style.disabled]: this.state.loading })}>
        <Link to={link(getOrder(1))} label="部门/项目组/个人"
          className={cx(style.filter, { [style.active]: active(1) })}
        />
        <div style={{ marginLeft: '60px' }}>
          <span>目标</span>
        </div>
        <Link to={link(getOrder(2))} label="优先级"
          className={cx(style.filter, style['priority-filter'], { [style.active]: active(2) })}
          style={{ marginLeft: '234px' }}
        />
        <Link to={link(getOrder(3))} label="截止日"
          className={cx(style.filter, [style['deadline-filter']], { [style.active]: active(3) })}
        />
        <Link to={link(getOrder(4))} label="进度"
          className={cx(style.filter, { [style.active]: active(4) })}
          style={{ marginLeft: '70px' }}
        />
        <div style={{ marginLeft: '220px' }}>
          <span>负责人</span>
        </div>
        <Link to={link(getOrder(5))} label="最后更新"
          className={cx(style.filter, { [style.active]: active(5) })}
          style={{ marginLeft: '127px' }}
        />
      </div>
    );
  }

  renderList() { // 列表
    const { all } = this.props.okr; // 获取列表数据
    const { totalNumber, objectiveVOList } = all || {};
    if (all == null) return <Loading small style={{ marginTop: '10px', marginLeft: '24px' }} />;
    return (
      <div className={cx(style.list, {
        [style['list-null']]: !objectiveVOList.length
      })}>
        {
          objectiveVOList.map((v, i) => (
            <ObjectiveItem key={i} {...v}/>
          ))
        }
        {
          !objectiveVOList.length ? (
            <div style={{textAlign: 'center'}}>
              <div style={{ margin: 'auto', borderRadius: '50%', backgroundImage: `url(${IMAGES_PATH}/objective-null.png)`, backgroundRepeat: 'no-repeat', backgroundPosition: '50% 50%', width: '160px', height: '160px' }}/>
              <p style={{ display: 'inline-block', marginTop: '15px', fontSize: '18px', color: 'rgb(153, 153, 153)' }}>没有符合条件的目标</p>
            </div>
          ) : null
        }
      </div>
    );
  }

  renderPager() { // 分页
    const { all } = this.props.okr;
    const {totalNumber } = all || {};
    if (all == null) return null;
    const { query } = this.props.location;
    const { pageNumber=1 } = query;
    const pageLength = Math.ceil(totalNumber/this.pageSize)
    if (pageLength <= 1) return null

    return (
      <div className={style.pagin}>
        <ul>
          {
            new Array(pageLength+1).join('0').split('').map((v, i) => {
              return <li key={i}>
                <Link to={`/okr/objective-targetAll?${util.body({...query, pageNumber: i+1})}`}
                  className={cx({ 
                    [style.active]: pageNumber == i+1 
                  })}
                  label={`${i+1}`}/>
              </li>
            })
          }
        </ul>
      </div>
    )
  }

  render() {
    const { progressStatus, priority } = this.props.location.query;
    const { loading } = this.state;
    const { fullName } = this.props.okr.all ? this.props.okr.all.coreUserProfileVO : {fullName: ""};
    // console.log(this.props.okr.all);
    // console.log(this.props.okr);
    return (
      <div className={style.root}>
        <div className={style.nav}>
          <h1>{fullName !== "" ? fullName+"的相关目标:" : "用户的相关目标"}</h1>
          <div>
            <div>
              <label>优先级：</label>
              <Select disabled={loading} style={{ width: '85px' }}
                onChange={::this.handleChangePriority}
                value={priority == null ? '0' : `${+priority + 1}`}
                list={[ '全部', '极高', '高', '中', '低', ]}
                activeItem={(v, i, active) => (
                  <li key={i} style={{ paddingLeft: active? '35px': '25px', }}
                    className={cx(style.priority, style[`priority-${i}`], { [style.active]: active })} key={i}
                    data-value={i}>
                    <span>{v}</span>
                  </li>
                )}
                item={(v, i, active) => (
                  <li key={i} data-value={i}
                    className={cx(style.priority, style[`priority-${i}`], { [style.active]: active })} key={i}>
                    <span>{v}</span>
                  </li>
                )}
              />
            </div>
            <div>
              <label>进展情况：</label>
              <Select disabled={loading} style={{ width: '100px' }}
                onChange={::this.handleChangeProgress}
                value={progressStatus == null ? '0': `${+progressStatus - 1}`}
                list={[ '全部', '尚未开始', '正在进行', '接近完成', ]}
                item={(v, i, active) => (
                  <li key={i} data-value={i} >
                    <span>{v}</span>
                  </li>
                )}
              />
            </div>
          </div>
        </div>
        <div className={cx(style['list-wrapper'], {
          [style['no-priority-filter']]: this.props.location.query.priority != -1 && this.props.location.query.priority != null,
        })}>
          { this.renderFilter() }
          { this.renderList() }
          { this.renderPager() }
        </div>
      </div>
    );
  }
}